import Vue from 'vue'

const gio = window.gio

Vue.directive('analysis', {
  bind: function(el, binding) {
    const { value, arg } = binding
    value && value.apply(this)
    if (el.addEventListener) {
      el.addEventListener('click', fhandleClick)
    } else if (el.attachEvent) {
      el.attachEvent('onclick', fhandleClick)
    } else {
      throw new Error('事件绑定函数出错')
    }
    function fhandleClick(evt) {
      switch (arg) {
        case 'music':
          gio('track', 'Redenvelopesrain_bgm')
          console.log('----Redenvelopesrain_bgm gio----:')
          break
        case 'share':
          gio('track', 'Redenvelopesrain_share')
          console.log('----Redenvelopesrain_share gio----:')
          break
      }
    }
    console.log('el, binding------:', el.addEventListener, el.attachEvent)
  }
})
let initCountDown = null
let timer = null
Vue.directive('countdown', {
  update: function(el, binding) {
    const { value } = binding
    console.log('-----countdown-----', value.countDownTime, this)
    if (value.countDownTime === initCountDown) return
    if (!initCountDown) initCountDown = value.countDownTime
    else {
      clearTimeout(timer)
    }
    if (!value) return
    console.log('count down directive input', value)
    let date = new Date(parseInt(value.countDownTime))
    let cb = value.cb
    let now = new Date()
    let diff = date - now
    let hourUnit = 1000 * 60 * 60
    let minUnit = 1000 * 60
    let secUnit = 1000
    let hour, min, sec, returnVal

    function parseDate(diff) {
      if (diff > 0) {
        hour = Math.floor(diff / hourUnit)
        // console.log('hour', hour)
        min = Math.floor((diff % hourUnit) / minUnit)
        // console.log('min', min)
        sec = Math.floor(((diff % hourUnit) % minUnit) / secUnit)
        // console.log('sec', sec)
        if (hour < 10) hour = '0' + hour
        if (min < 10) min = '0' + min
        if (sec < 10) sec = '0' + sec
        if (hour > 0) {
          returnVal = `${hour}时${min}分${sec}秒`
        } else {
          returnVal = `${min}分${sec}秒`
        }
      } else {
        returnVal = `00分00秒`
      }
      el.innerHTML = returnVal

      if (diff - 1000 > 0) {
        timer = setTimeout(() => {
          parseDate(diff - 1000)
        }, 1000)
      } else {
        console.log('>>>>>>>>>>>>>>>>>>>>I am being zero', diff)
        cb && cb.apply(this)
      }
    }
    parseDate(diff)
  }
})
